<template>
   <div class="list_container">
      <div style="display: flex; justify-content: space-between">
         <el-breadcrumb
            separator-class="el-icon-arrow-right"
            style="margin-top: 10px; margin-left: 4px"
         >
            <el-breadcrumb-item style="font-size: 16px"
               >系统管理</el-breadcrumb-item
            >
            <el-breadcrumb-item>
               <span style="color: #409eff; font-size: 16px">权限管理</span>
            </el-breadcrumb-item>
         </el-breadcrumb>

         <el-button
            v-if="currentPagePermissionStatusByCurrentUser.createPermission"
            style="
               width: 140px;
               line-height: 50px;
               margin-right: 15px;
               margin-top: 14px;
            "
            @click="createPermissionDialogShow = true"
         >
            <el-icon style="margin-right: 4px; vertical-align: middle">
               <CirclePlus />
            </el-icon>
            新增权限
         </el-button>
      </div>

      <!-- 权限列表 -->
      <div style="margin-top: 30px">
         <el-table
            style="border-radius: 10px"
            :data="permissions"
            stripe
            :header-cell-style="{ height: '60px', fontSize: '16px' }"
            :cell-style="{ height: '60px', fontSize: '14px' }"
            :default-expand-all="false"
         >
            <el-table-column
               prop="num"
               label="序号"
               header-align="center"
               width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="permissionLevel"
               label="权限层次"
               header-align="center"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="permissionName"
               label="权限名称"
               header-align="center"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="permissionDescription"
               label="权限描述"
               header-align="center"
               align="center"
            >
            </el-table-column>
            <el-table-column
               v-if="
                  currentPagePermissionStatusByCurrentUser.operatePermissionList
               "
               label="操作"
               width="240px"
               header-align="center"
               align="center"
            >
               <template v-slot="scope">
                  <el-tooltip
                     effect="dark"
                     placement="top-start"
                     content="编辑此权限描述信息"
                  >
                     <el-icon
                        @click="editPermissionDes(scope.row)"
                        style="font-size: 21px; color: #5a9cf8; cursor: pointer"
                     >
                        <Edit />
                     </el-icon>
                  </el-tooltip>
               </template>
            </el-table-column>
         </el-table>
      </div>

      <!-- 编辑权限描述信息 -->
      <el-dialog
         v-model="eidtPermissionDesDialogShow"
         width="500px"
         :showClose="false"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 18px">{{
               editPermissionDesForm.permissionName
            }}</span>
         </template>

         <el-form :model="editPermissionDesForm">
            <el-form-item
               style="margin-left: -28px"
               label="权限描述"
               label-width="100"
               prop="telephone"
            >
               <el-input
                  style="width: 380px"
                  v-model="editPermissionDesForm.permissionDescription"
                  placeholder="请输入权限描述："
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <el-button @click="eidtPermissionDesDialogShow = false"
               >取 消</el-button
            >
            <el-button type="primary" @click="confimEditPermissionDes()"
               >修 改</el-button
            >
         </template>
      </el-dialog>

      <!-- 新增权限 -->
      <el-dialog
         v-model="createPermissionDialogShow"
         width="525px"
         :show-close="false"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 20px; font-weight: 400; margin: 0"
               >新增权限</span
            >
         </template>

         <el-form
            :model="createPermissionForm"
            :rules="createPermissionRules"
            ref="createPermissionFormDom"
         >
            <el-form-item
               label="权限名称："
               style="margin-left: 10px"
               prop="permissionName"
            >
               <el-input
                  v-model="createPermissionForm.permissionName"
                  style="width: 80%"
               ></el-input>
            </el-form-item>

            <el-form-item
               label="权限路径："
               prop="permissionPath"
               style="margin-left: 10px"
            >
               <el-input
                  v-model="createPermissionForm.permissionPath"
                  style="width: 80%"
               ></el-input>
            </el-form-item>

            <el-form-item
               label="权限层级："
               prop="permissionLevel"
               style="margin-left: 10px"
            >
               <el-input
                  v-model="createPermissionForm.permissionLevel"
                  style="width: 80%"
               ></el-input>
            </el-form-item>

            <el-form-item
               label="权限描述："
               prop="permissionDescription"
               style="margin-left: 20px"
            >
               <el-input
                  v-model="createPermissionForm.permissionDescription"
                  style="width: 80%"
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <span class="dialog-footer">
               <el-button @click="createPermissionDialogShow = false"
                  >取 消</el-button
               >
               <el-button type="primary" @click="createPermission()"
                  >确 定</el-button
               >
            </span>
         </template>
      </el-dialog>
   </div>
</template>

<script>
import $axios from "@/axios";
import { useStore } from "vuex";
import router from "@/rooter";
import { onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";

export default {
   name: "权限管理",
   setup() {
      const store = useStore();

      // 当前页当前用户权限
      let currentPagePermissionStatusByCurrentUser = reactive({
         permissionManagementPageShow: false,
         createPermission: true,
         operatePermissionList: false,
      });

      // 系统权限信息
      let permissions = ref([]);

      // 控制编辑权限描述信息dialog是否显示
      let eidtPermissionDesDialogShow = ref(false);

      // 权限修改表单
      let editPermissionDesForm = reactive({
         permissionId: "",
         permissionName: "",
         permissionDescription: "",
         permissionDescriptionOrigin: "",
      });

      // 修改权限描述
      function editPermissionDes(row) {
         eidtPermissionDesDialogShow.value = true;

         editPermissionDesForm.permissionId = row.id;
         editPermissionDesForm.permissionName = row.permissionName;
         editPermissionDesForm.permissionDescription =
            row.permissionDescription;
         editPermissionDesForm.permissionDescriptionOrigin =
            row.permissionDescription;
      }

      // 确认修改
      function confimEditPermissionDes() {
         // 如果权限描述未发生改变，则直接关闭窗口
         if (
            editPermissionDesForm.permissionDescriptionOrigin ===
            editPermissionDesForm.permissionDescription
         ) {
            eidtPermissionDesDialogShow.value = false;
            return;
         }

         // 发送请求，修改权限描述
         $axios
            .post(
               "/permission/updatePermissionDescription",
               editPermissionDesForm
            )
            .then(() => {
               ElMessage({
                  type: "success",
                  message: "权限描述修改成功",
                  duration: 1000,
               });

               setTimeout(() => {
                  window.location.reload();
               }, 1000);
            });
      }

      // ===============================

      // 控制新增权限窗口是否显示
      let createPermissionDialogShow = ref(false);

      // 新增权限表单
      let createPermissionForm = reactive({
         permissionName: "",
         permissionLevel: "",
         permisssionPath: "",
         permissionDescription: "",
      });

      // 新增权限表单dom
      const createPermissionFormDom = ref(null);

      // 输入角色名的限制规则
      const createPermissionRules = {
         permissionName: [
            { required: true, message: "请输入权限名称", trigger: "blur" },
         ],
         permissionPath: [
            { required: true, message: "请输入权限路径", trigger: "blur" },
         ],
         permissionLevel: [
            { required: true, message: "请输入权限层级", trigger: "blur" },
         ],
      };

      // 新增权限请求
      function createPermission() {
         createPermissionFormDom.value.validate((valid) => {
            if (valid) {
               $axios
                  .post("/permission/createPermission", createPermissionForm)
                  .then(() => {
                     ElMessage({
                        type: "success",
                        message: "权限添加成功",
                        duration: 1000,
                     });

                     setTimeout(() => {
                        window.location.reload();
                     }, 1000);
                  });
            } else {
               ElMessage({
                  type: "error",
                  message: "请填写必填项",
                  duration: 2000,
               });
            }
         });
      }

      // 等待vuex中的userPermission准备好
      function waitForPermissions() {
         return new Promise((resolve) => {
            store.watch(
               () => store.state.currentLoginUser.permissions,
               (newValue) => {
                  // 权限：
                  // 1.新增权限
                  // 2.操作权限列表
                  if (newValue) {
                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath ===
                           "/systemManagement/permissionManagement"
                        ) {
                           currentPagePermissionStatusByCurrentUser.permissionManagementPageShow = true;
                        }
                        if (
                           permission.permissionPath ===
                           "/systemManagement/permissionManagement/operatePermission"
                        ) {
                           currentPagePermissionStatusByCurrentUser.operatePermissionList = true;
                        }
                     });

                     // 将 Promise 状态改为已完成
                     resolve();
                  }
               },
               {
                  immediate: true, // 立即监听
               }
            );
         });
      }

      // 发送请求获取用户数据
      onMounted(async () => {
         await waitForPermissions();

         if (
            !currentPagePermissionStatusByCurrentUser.permissionManagementPageShow
         ) {
            ElMessage({
               type: "error",
               message: "用户无权限",
               duration: 1500,
            });
            router.go(-1);
            return;
         }

         // 获取系统所有权限
         $axios.get("/permission/allPermissions").then((resp) => {
            for (let i = 0; i < resp.data.data.length; i++) {
               resp.data.data[i].num = i + 1;
            }

            permissions.value = resp.data.data;
         });
      });

      return {
         permissions,
         eidtPermissionDesDialogShow,
         editPermissionDes,
         confimEditPermissionDes,
         editPermissionDesForm,
         createPermissionForm,
         createPermissionDialogShow,
         createPermissionFormDom,
         createPermissionRules,
         createPermission,
         currentPagePermissionStatusByCurrentUser,
      };
   },
};
</script>

<style>
</style>